import 'dart:convert';
import 'dart:typed_data';

import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_email_ui/components/side_menu.dart';
import 'package:flutter/foundation.dart' show kIsWeb;
import 'package:flutter_email_ui/models/Email.dart';
import 'package:flutter_email_ui/screens/email/demo_first.dart';
import 'package:flutter_email_ui/screens/email/demo_second.dart';
import 'package:flutter_email_ui/screens/email/email_screen.dart';
import 'package:flutter_svg/flutter_svg.dart';
import 'package:flutter_usb_printer/flutter_usb_printer.dart';

import '../../../constants.dart';
import '../../../responsive.dart';
import 'email_card.dart';

class ListOfEmails extends StatefulWidget {
  const ListOfEmails({Key key}) : super(key: key);

  @override
  _ListOfEmailsState createState() => _ListOfEmailsState();
}

class _ListOfEmailsState extends State<ListOfEmails> {
  final GlobalKey<ScaffoldState> _scaffoldKey = GlobalKey<ScaffoldState>();
  List<Map<String, dynamic>> devices = [];
  FlutterUsbPrinter flutterUsbPrinter = FlutterUsbPrinter();
  bool connected = false;
  @override
  Widget build(BuildContext context) {
    return Scaffold(
        key: _scaffoldKey,
        drawer: ConstrainedBox(
          constraints: BoxConstraints(maxWidth: 250),
          child: SideMenu(),
        ),
        body: Container(
          padding: EdgeInsets.only(top: kIsWeb ? kDefaultPadding : 0),
          color: kBgDarkColor,
          child: SafeArea(
            right: false, //让在pc端右端展示比较完整
            child: Column(
              children: [
                // 顶部搜索框
                Padding(
                  padding: EdgeInsets.symmetric(horizontal: kDefaultPadding),
                  child: Row(
                    children: [
                      InkWell(
                        child: Text("点我调试打印机: ${devices.length}"),
                        onTap: _testPrinter,
                      ),
                      // 改菜单栏在PC端不展示
                      if (!Responsive.isDesktop(context))
                        IconButton(
                          icon: Icon(Icons.menu),
                          onPressed: () {
                            _scaffoldKey.currentState.openDrawer();
                          },
                        ),
                      if (!Responsive.isDesktop(context)) SizedBox(width: 5),
                      Expanded(
                        child: TextField(
                          onChanged: (value) {},
                          decoration: InputDecoration(
                            hintText: "Search",
                            fillColor: kBgLightColor,
                            filled: true,
                            suffixIcon: Padding(
                              padding: EdgeInsets.all(kDefaultPadding * 0.75),
                              child: SvgPicture.asset(
                                "assets/Icons/Search.svg",
                                width: 24,
                              ),
                            ),
                            border: OutlineInputBorder(
                              borderRadius: BorderRadius.all(
                                Radius.circular(10),
                              ),
                              borderSide: BorderSide.none,
                            ),
                          ),
                        ),
                      ),
                    ],
                  ),
                ),
                SizedBox(height: kDefaultPadding),
                ...devices
                    .map((device) => new ListTile(
                          onTap: () {
                            _connect(int.parse(device['vendorId']),
                                int.parse(device['productId']));
                          },
                          leading: new Icon(Icons.usb),
                          title: new Text(device['manufacturer'] +
                              " " +
                              device['productName']),
                          subtitle: new Text(
                              device['vendorId'] + " " + device['productId']),
                        ))
                    .toList(),
                InkWell(
                  child: Text("触发打印"),
                  onTap: _print,
                ),
                // 引导
                Padding(
                  padding: EdgeInsets.symmetric(horizontal: kDefaultPadding),
                  child: Row(
                    children: [
                      SvgPicture.asset("assets/Icons/Angle down.svg",
                          width: 16, color: Colors.black),
                      SizedBox(width: 5),
                      Text(
                        "Sort by Date",
                        style: TextStyle(fontWeight: FontWeight.w500),
                      ),
                      Spacer(),
                      MaterialButton(
                          minWidth: 20,
                          onPressed: () {},
                          child: SvgPicture.asset(
                            "assets/Icons/Sort.svg",
                            width: 16,
                          )),
                    ],
                  ),
                ),
                SizedBox(height: kDefaultPadding),
                Expanded(
                  child: ListView.builder(
                    itemCount: emails.length,
                    itemBuilder: (context, index) => EmailCard(
                      isActive:
                          Responsive.isMobile(context) ? false : index == 0,
                      email: emails[index],
                      press: () {
                        // 切换到其他页面
                        if (index == 0) {
                          Navigator.push(
                            context,
                            MaterialPageRoute(
                              builder: (context) => DemoFirst(),
                            ),
                          );
                        } else if (index == 1) {
                          Navigator.push(
                            context,
                            MaterialPageRoute(
                              builder: (context) => DemoSecond(),
                            ),
                          );
                        } else {
                          Navigator.push(
                            context,
                            MaterialPageRoute(
                              builder: (context) =>
                                  EmailScreen(email: emails[index]),
                            ),
                          );
                        }
                      },
                    ),
                  ),
                ),
              ],
            ),
          ),
        ));
  }

  // 测试USB打印机
  void _testPrinter() async {
    print("test---printer");
    List<Map<String, dynamic>> results = [];
    results = await FlutterUsbPrinter.getUSBDeviceList();

    print(" length: ${results.length}");
    setState(() {
      devices = results;
    });
  }

  _print() async {
    try {
      var data = Uint8List.fromList(
          utf8.encode(" Hello world Testing ESC POS printer..."));
      await flutterUsbPrinter.write(data);
      // await FlutterUsbPrinter.printRawData("text");
      // await FlutterUsbPrinter.printText("Testing ESC POS printer...");
    } on PlatformException {
      //response = 'Failed to get platform version.';
    }
  }

  _connect(int vendorId, int productId) async {
    bool returned = false;
    try {
      returned = await flutterUsbPrinter.connect(vendorId, productId);
    } on PlatformException {
      //response = 'Failed to get platform version.';
    }
    if (returned) {
      setState(() {
        connected = true;
      });
    }
  }
}
